package com.central.post.job

import cn.hutool.core.date.DateUnit
import cn.hutool.core.date.DateUtil
import com.central.common.feign.UserService
import com.central.common.model.NewGoodPushParam
import com.central.common.utils.formatStandard
import com.central.post.mq.PostSink
import com.central.post.mq.sendNewGoodSubscribe
import com.central.post.service.NewGoodService
import com.xxl.job.core.biz.model.ReturnT
import com.xxl.job.core.handler.IJobHandler
import com.xxl.job.core.handler.annotation.JobHandler
import com.xxl.job.core.log.XxlJobLogger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*

/**
 * 任务Handler示例（Bean模式）
 *
 *
 * 开发步骤：
 * 1、继承"IJobHandler"：“com.xxl.job.core.handler.IJobHandler”；
 * 2、注册到Spring容器：添加“@Component”注解，被Spring容器扫描为Bean实例；
 * 3、注册到执行器工厂：添加“@JobHandler(value="自定义jobhandler名称")”注解，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 4、执行日志：需要通过 "XxlJobLogger.log" 打印执行日志；
 *
 * @author xuxueli 2015-12-19 19:43:36
 */
@JobHandler(value = "pushTaskHandler")
@Component
class PushTaskJobHandler : IJobHandler() {


    @Autowired
    private lateinit var newGoodService: NewGoodService

    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var postSink: PostSink


    @Throws(Exception::class)
    override fun execute(param: String): ReturnT<String> {

        //1. 找到上新商品时间大于或者等于的间隔在10分钟以内的
        newGoodService.list().filter {
            when(DateUtil.between(DateUtil.parseDateTime(it.goodTime), Date(), DateUnit.MINUTE,false)) {
                in 0 .. 10 -> true
                else -> false
            }
        }.forEach {

            XxlJobLogger.log(">>>>>>>>>>>>>>>>>>>>>开始推送用户")
            it.subscribeUser?.run {
                postSink.sendNewGoodSubscribe(
                    NewGoodPushParam()
                        .apply {
                            openId = it.subscribeUser?.split(",")?.mapNotNull { userService.selectByUserId(it.toLong())?.openId }
                            goodName = it.goodName
                            goodDetail = it.goodBrand
                            goodTime = it.createTime.formatStandard()
                            goodPrice = it.goodPrice
                            goodId = it.id
                        }, null)
            }
        }

        return SUCCESS
    }
}
